package artid.com.arttogoa;

import java.util.ArrayList;
import java.util.List;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import artid.com.arttogoa.R;

import artid.com.arttogoa.barcode.Bimp;
import artid.com.arttogoa.glide.GlideUtil;
import artid.com.arttogoa.parser.FilesBean;
import artid.com.arttogoa.photo.ImagePagerActivity;
import artid.com.arttogoa.util.BitmapUtil;
import artid.com.arttogoa.util.CameraUtils;
import artid.com.arttogoa.util.NetUtils;

public class LocalAlbumActivity extends Activity implements OnClickListener {
	private GridView gv;
	private Handler mHandler;
	private List<FilesBean> filesList = new ArrayList<FilesBean>();
	private List<FilesBean> selectFiles = new ArrayList<FilesBean>();
	private Activity mContext;
	private LinearLayout complete;
	private TextView sum, cText,title_canalBtn;
	private RelativeLayout relSum;


	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@SuppressLint("HandlerLeak")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_driver_photo);
		mContext = this;
		gv = (GridView) findViewById(R.id.grid);
		complete = (LinearLayout) findViewById(R.id.ll_complete);
		relSum = (RelativeLayout) findViewById(R.id.rel_sum);
		complete.setOnClickListener(this);
		sum = (TextView) findViewById(R.id.tv_num);
		cText = (TextView) findViewById(R.id.tv_ctext);
		title_canalBtn = (TextView) findViewById(R.id.title_canal);
		title_canalBtn.setOnClickListener(this);
		gv.setVisibility(View.VISIBLE);
		// gv.setOnItemClickListener(new OnItemClickListener() {
		// @Override
		// public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
		// long arg3) {
		// // TODO Auto-generated method stub
		//
		// }
		// });
		getAll();
		setSum();
		mHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {

				super.handleMessage(msg);
				switch (msg.what) {
				case 1:
					gv.setAdapter(new AlbumAdapter(mContext));
				}
			}

		};
	}

	private void getAll() {
		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {

			return;
		}
		//
		// 显示进度条
		new Thread(new Runnable() {

			@Override
			public void run() {
				Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				ContentResolver mContentResolver = mContext
						.getContentResolver();

				// 只查询jpeg和png的图片
				Cursor mCursor = mContentResolver.query(mImageUri, null,
						MediaStore.Images.Media.MIME_TYPE + "=? or "
								+ MediaStore.Images.Media.MIME_TYPE + "=?",
								new String[] { "image/jpeg", "image/png" },
								MediaStore.Images.Media.DATE_ADDED + " DESC");

				while (mCursor.moveToNext()) {
					// 获取图片的路径
					String path = mCursor.getString(mCursor
							.getColumnIndex(MediaStore.Images.Media.DATA));
					String text = mCursor.getString(mCursor
							.getColumnIndex(MediaStore.Images.Media.TITLE));
					String size = mCursor.getString(mCursor
							.getColumnIndex(MediaStore.Images.Media.SIZE));
					FilesBean fb = new FilesBean();
					fb.setImgURL(path);
					fb.setName(text);
					fb.setFileSize(size);
					fb.setSelected(false);
					filesList.add(fb);
				}
				System.out.println("filesList=" + filesList.toString());
				mCursor.close();

				// 通知Handler扫描图片完成
				mHandler.sendEmptyMessage(1);

			}
		}).start();

	}

	public class AlbumAdapter extends BaseAdapter implements OnClickListener {

		private Context mContext;

		// ImageLoader mImageLoader;

		public AlbumAdapter(Context context) {
			this.mContext = context;
			// RequestQueue mQueue = Volley.newRequestQueue(context);
			// mImageLoader = new ImageLoader(mQueue, new BitmapCache());
		}

		@Override
		public int getCount() {
			return filesList != null ? filesList.size() + 1 : 1;
		}

		@Override
		public Object getItem(int position) {
			return filesList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@SuppressWarnings("null")
		@SuppressLint("InflateParams")
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder vh = null;
			final int index = position - 1;
			if (convertView == null) {
				vh = new ViewHolder();
				convertView = LayoutInflater.from(mContext).inflate(
						R.layout.item_grid_album, null);
				vh.selectBtn = (ImageView) convertView
						.findViewById(R.id.iv_select);
				vh.select = (RelativeLayout) convertView
						.findViewById(R.id.rel_select);
				vh.iv = (ImageView) convertView.findViewById(R.id.icon);
				vh.photograph = (RelativeLayout) convertView
						.findViewById(R.id.rel_photograph);
				convertView.setTag(vh);
			} else {
				vh = (ViewHolder) convertView.getTag();
			}
			/** 首先判断是否是首个，如果是则加载拍照按钮 */
			if (index == -1) {
				vh.photograph.setVisibility(View.VISIBLE);
				vh.photograph.setOnClickListener(this);
			}
			/** 如果不是，则加载普通相片 */
			else {
				vh.photograph.setVisibility(View.GONE);
				final FilesBean item = filesList.get(index);
				if (item.isSelected()) {
					vh.selectBtn.setImageResource(R.drawable.photo_choice_sel);
				} else {
					vh.selectBtn.setImageResource(R.drawable.photo_choice_nor);
				}
				vh.select.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (filesList.get(index).isSelected()) {
							filesList.get(index).setSelected(false);
							drrChenge(item);
						} else {
							if (Bimp.drr.size() + selectFiles.size() < 9) {
								selectFiles.add(item);
								filesList.get(index).setSelected(true);
							} else {
								Toast.makeText(mContext,
										"最多只能选" + (9 - Bimp.drr.size()) + "张",
										2).show();
							}
						}
						setSum();
						notifyDataSetChanged();
					}
				});
				String url = item.getImgURL();
				GlideUtil.setImage(mContext, url, R.drawable.yspba_img_mor,
						R.drawable.yspba_img_mor, vh.iv);
				// Glide.with(mContext).load(url)
				// .placeholder(R.drawable.yspba_img_mor)
				// .centerCrop()
				// .error(android.R.drawable.ic_delete).into(vh.iv);
				if (position == getCount()) {
					notifyDataSetChanged();
				}
			}
			vh.iv.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					imageBrower(index);
				}
			});
			return convertView;
		}

		private void drrChenge(FilesBean b) {
			String path = b.getImgURL();
			for (int i = 0; i < selectFiles.size(); i++) {
				if (path.equals(selectFiles.get(i).getImgURL()))
					selectFiles.remove(i);
			}
		}

		class ViewHolder {
			ImageView iv, selectBtn;
			RelativeLayout photograph, select;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.view.View.OnClickListener#onClick(android.view.View)
		 */
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.rel_photograph:
				//检查权限
				if (ContextCompat.checkSelfPermission(LocalAlbumActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
					displayFrameworkBugMessageAndExit();
					return;
				}
				CameraUtils.openCameraImage(LocalAlbumActivity.this);
				break;
			default:
				break;
			}
		}
	}
	/**
	 * 若摄像头被占用或者摄像头有问题则跳出提示对话框
	 */
	private void displayFrameworkBugMessageAndExit() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.app_name));
		builder.setMessage("请设置开启摄像头权限");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				NetUtils.getAppDetailSettingIntent(mContext);
			}
		});
		builder.show();
	}



	/**
	 * 打开图片查看器
	 * 
	 * @param position
	 * @param urls2
	 */
	protected void imageBrower(int position) {
		ArrayList<String> urls2 = new ArrayList<String>();
		for (int i = 0; i < filesList.size(); i++) {
			urls2.add(filesList.get(i).getImgURL());
		}
		Intent intent = new Intent(mContext, ImagePagerActivity.class);
		// 图片url,为了演示这里使用常量，一般从数据库中或网络中获取
		intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, urls2);
		intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
		intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_TYPE,
				ImagePagerActivity.LATTICE);
		mContext.startActivity(intent);
	}

	/**
	 * 
	 */
	private void setSum() {
		// TODO Auto-generated method stub
		if (selectFiles.size() > 0) {
			cText.setTextColor(sum.getResources().getColor(R.color.select));
			sum.setText(String.valueOf(selectFiles.size()));
			relSum.setVisibility(View.VISIBLE);
			complete.setClickable(true);
		} else {
			cText.setTextColor(sum.getResources().getColor(R.color.unselect));
			relSum.setVisibility(View.GONE);
			complete.setClickable(false);
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == CameraUtils.GET_IMAGE_BY_CAMERA) {
			final Uri uri = CameraUtils.imageUriFromCamera;
			if(uri!=null){
				String path = BitmapUtil.getRealFilePath(mContext, uri);
				final BitmapFactory.Options options = new BitmapFactory.Options();
				/**
				 * 最关键在此，把options.inJustDecodeBounds = true;
				 * 这里再decodeFile()，返回的bitmap为空 ，但此时调用options.outHeight时，已经包含了图片的高了
				 */
				options.inJustDecodeBounds = true;
				Bitmap bitmap1 = BitmapFactory.decodeFile(path,options); // 此时返回的bitmap为null
				int outHeight = options.outHeight;
				if(outHeight==0){
					return;
				}
				FilesBean FB = new FilesBean();
				FB.setImgURL(path);
				Bimp.drr.add(FB);
				finish();
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.ll_complete:
			for (int i = 0; i < selectFiles.size(); i++) {
				Bimp.drr.add(selectFiles.get(i));
			}
			finish();
			break;
		case R.id.title_canal:
			finish();
			break;
		default:
			break;
		}
	}
}
